<?php
session_start();
require('include/twitteroauth.php');
require('config.php');

if (isset($_GET['u']) && isset($_GET['p'])) {
    $connection = new TwitterOAuth(OAUTH_KEY, OAUTH_SECRET);
    $request_token = $connection->getRequestToken(TWIP_BASE_URL.'oauth.php');

    /* Save request token to session */
    $_SESSION['oauth_token'] = $request_token['oauth_token'];
    $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
    
    if ($connection->http_code == 200) {
        /* Build authorize URL */
        $url = $connection->getAuthorizeURL($_SESSION['oauth_token']);
        header('HTTP/1.1 302 Found');
        header('Status: 302 Found');
        header('Location: oauth_proxy.php?u=' . $_GET['u'] . '&p=' . $_GET['p'] . '&g=' . urlencode($url));
        
    } else {
        $msg = 'Could not connect to Twitter. Refresh the page or try again later.';
        if($connection->http_code==0){
            $msg .= "<br />Don't report bugs or issues if you got this error code.Please try a paid virtual host.";
        }
        header('Location: ' . DABR_URL . 'login?msg=' . urlencode($msg));
    }
    exit();
    
} else if(isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {

    $connection = new TwitterOAuth(OAUTH_KEY, OAUTH_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
    $access_token = $connection->getAccessToken($_GET['oauth_verifier']);
    
    if($connection->http_code == 200){
        if (MYSQL_USERS == 'ON') {
            // Delete old tokens
            $old_tokens = glob('oauth/'.$access_token['screen_name'].'.*');
            if(!empty($old_tokens)){
                foreach($old_tokens as $file){
                    unlink($file);
                }
            }
            
            // Generate OAuth api suffix
            $suffix_string = '';
            for ($i=0; $i<6; $i++) {
                $d=rand(1,30)%2;
                $suffix_string .= $d ? chr(rand(65,90)) : chr(rand(48,57));
            }
            
            if(file_put_contents('oauth/'.$access_token['screen_name'].'.'.$suffix_string,serialize($access_token)) === FALSE){
                echo 'Error failed to write access_token file.Please check if you have write permission to oauth/ directory'."\n";
                exit();
            }

            // Save user info to database
            $sql = sprintf("UPDATE user SET oauth_key='%s', oauth_secret='%s', twip_oapi='%s' WHERE username='%s' LIMIT 1", mysql_escape_string($access_token['oauth_token']), mysql_escape_string($access_token['oauth_token_secret']),  mysql_escape_string($suffix_string), mysql_escape_string($access_token['screen_name']));
            db_query($sql);
        }
        
        $GLOBALS['user']['username'] = $access_token['screen_name'];
        $GLOBALS['user']['password'] = $access_token['oauth_token'] . '|' . $access_token['oauth_token_secret'];
        $GLOBALS['user']['type'] = 'oauth';
        _user_save_cookie($_SESSION['stay-logged-in']);
        
        //$url = BASE_URL.'o/'.$access_token['screen_name'].'/'.$suffix_string;
        header('HTTP/1.1 302 Found');
        header('Status: 302 Found');
        header('Location: ' . DABR_URL);
        
    } else {
        header('HTTP/1.1 302 Found');
        header('Status: 302 Found');
        header('Location: ' . DABR_URL . 'login?msg='.urlencode('HTTP error code '.$connection->http_code));
        /*
        echo 'Error '.$connection->http_code."\n";
        print_r($connection);
        */
    }
    exit();
}

function _user_save_cookie($stay_logged_in = 0) {
	$cookie = _user_encrypt_cookie();
	$duration = 0;
	if ($stay_logged_in) {
		$duration = time() + (3600 * 24 * 365);
	}
	setcookie('USER_AUTH', $cookie, $duration, '/');
}

function _user_encryption_key() {
	return ENCRYPTION_KEY;
}

function _user_encrypt_cookie() {
	$plain_text = $GLOBALS['user']['username'] . ':' . $GLOBALS['user']['password'] . ':' . $GLOBALS['user']['type'];

	$td = mcrypt_module_open('blowfish', '', 'cfb', '');
	$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	mcrypt_generic_init($td, _user_encryption_key(), $iv);
	$crypt_text = mcrypt_generic($td, $plain_text);
	mcrypt_generic_deinit($td);
	return base64_encode($iv.$crypt_text);
}
?>
